package com.yy.example.jpa.test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;

/**
 * AnyTable..
 *
 * @author Lizhong
 * @date 2019/7/25
 */
@Component
public class AnyTable  implements ApplicationRunner {
    @PersistenceContext //注入的是实体管理器,执行持久化操作
            EntityManager entityManager;
@Autowired
DynamicRepository dynamicRepository;



    public List<Object[]> selectByTableNameAndAttr() {
        String sql="select * from test_07_23_07_32_00 where id =?2";


        Query nativeQuery = entityManager.createNativeQuery(sql, DynamicTable.class);
        // nativeQuery.setParameter(1,"test_07_23_07_32_00");
        nativeQuery.setParameter(2,"1");
        List resultList = nativeQuery.getResultList();
        String count="select count(id) from test_07_23_07_32_00 ";
        Query nativeQuery1 = entityManager.createNativeQuery(count);
        Object singleResult = nativeQuery1.getSingleResult();
        System.out.println(singleResult);

        return  null;

    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // selectByTableNameAndAttr();
        // 测试@where注解
        // while (true){
            dynamicRepository.findAll();
            Thread.currentThread().sleep(1000);
            List<DynamicTable> id = dynamicRepository.findAll(new Specification<DynamicTable>() {
                @Override
                public Predicate toPredicate(Root<DynamicTable> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                    Path<Boolean> id = root.get("id");
                    // return criteriaBuilder.;
                  return   criteriaBuilder.conjunction();
                    // return criteriaBuilder.equal(id, "2");
                }
            });
        // }
    }
}
